﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Friso.Entities;
using Friso.Business;
using FetCo.Data;
using FetCo.Framework;
public partial class Fetco_Category : System.Web.UI.Page
{
    #region viewstate
    public int NoCountStart
    {
        get { return Convert.ToInt32(ViewState["NoCountStart"]); }
        set { ViewState["NoCountStart"] = value; }
    }
    protected string hidColSort
    {
        get
        {
            object o = ViewState["hidColSort"];
            if (o == null) return "[" + Article._Table + "].[" + ArticleColumns.Order + "]";
            return o.ToString();
        }
        set
        {
            ViewState["hidColSort"] = value;
        }
    }
    public string Title
    {
        get
        {
            if (HttpContext.Current.Request.QueryString["Title"] == null)
                return "";
            else
                return HttpContext.Current.Request.QueryString["Title"];
        }
    }
    public long StatusID
    {
        get
        {
            if (HttpContext.Current.Request.QueryString["StatusID"] == null)
                return long.MinValue;
            else
                return long.Parse(HttpContext.Current.Request.QueryString["StatusID"]);
        }
    }
    public DateTime CreatedDate
    {
        get
        {
            if (HttpContext.Current.Request.QueryString["CreatedDate"] == null)
                return DateTime.Parse(FetConstant.DateDefault);
            else
                return Utilitys.ParseDateTime(HttpContext.Current.Request.QueryString["CreatedDate"]);
        }
    }
    public long UserID
    {
        get
        {
            if (HttpContext.Current.Request.QueryString["UserID"] == null)
                return long.MinValue;
            else
                return long.Parse(HttpContext.Current.Request.QueryString["UserID"]);
        }
    }
    public long SubCatId
    {
        get
        {
            if (HttpContext.Current.Request.QueryString["SubCatId"] == null)
                return long.MinValue;
            else
                return long.Parse(HttpContext.Current.Request.QueryString["SubCatId"]);
        }
    }
    public string _Date
    {
        get
        {
            if (HttpContext.Current.Request.QueryString["CreatedDate"] == null)
                return "";
            else
                return HttpContext.Current.Request.QueryString["CreatedDate"];
        }

    }
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["CurrentMenu"] = (int)Menus.Article;
        Session["SubCurrentMenu"] = (int)SubMenus.ListArticle;
        if (IsPostBack)
            return;
        LoadddlStatus(ddlStatusSearch);
        LoadData();
        txtTitle.Text = this.Title;
        ddlStatusSearch.SelectedValue = this.StatusID.ToString();
        load_sub();
    }
    private string username = string.Empty;
    private void load_sub()
    {
        ddlsub.Items.Clear();
        ddlsub.Items.Add(new ListItem((string)Utilitys.Dictionary["option"], "0"));
        SubCategoryCollection _SubCategoryCollection = SubCategoryService.GetSubCategoryList(SubCategoryColumns.Code, OrderDirection.ASC);
        foreach (SubCategory _SubCategory in _SubCategoryCollection)
        {
            ddlsub.Items.Add(new ListItem(_SubCategory.Name, _SubCategory.SubCategoryID.ToString()));
        }
    }
    protected void LoadData()
    {

        Criteria cri = new Criteria();
        cri.addJoin(Statu._Table, "[" + Article._Table + "].[" + ArticleColumns.Status + "]", "[" + Statu._Table + "].[" + StatuColumns.StatusId + "]", Condition.EQUAL, Condition.LEFT_JOIN);
        cri.addJoin("[" + Friso.Entities.User._Table + "]", "[" + Article._Table + "].[" + ArticleColumns.CreatedBy + "]", "[" + Friso.Entities.User._Table + "].[" + UserColumns.UserId + "]", Condition.EQUAL, Condition.LEFT_JOIN);
        if (UserRight.GetUserPermission() == FetConstant.TacGia)
            cri.add("[" + Article._Table + "].[" + ArticleColumns.CreatedBy + "]", UserRight.GetUserId(HttpContext.Current.User.Identity.Name), Condition.EQUAL, Condition.AND);
        if (!string.IsNullOrEmpty(this.Title))
            cri.add("[" + Article._Table + "].[" + ArticleColumns.Title + "]", this.Title, Condition.LIKE, Condition.AND);
        if (this.StatusID != long.MinValue && this.StatusID != 0)
            cri.add("[" + Article._Table + "].[" + ArticleColumns.Status + "]", this.StatusID, Condition.EQUAL, Condition.AND);
        if (this.CreatedDate != DateTime.Parse(FetConstant.DateDefault))
            cri.addShortDate("[" + Article._Table + "].[" + ArticleColumns.CreatedDate + "]", Utilitys.ParseDateTime(_Date), Condition.EQUAL, Condition.AND);
        if (this.UserID != long.MinValue && this.UserID != 0)
            cri.add("[" + Article._Table + "].[" + ArticleColumns.CreatedBy + "]", this.UserID, Condition.EQUAL, Condition.AND);
        if (this.SubCatId != 0 && this.SubCatId != long.MinValue)
        {
            cri.add("[" + Article._Table + "].[" + ArticleColumns.SubCatId + "]", this.SubCatId, Condition.EQUAL, Condition.AND);
        }
        string query = string.Empty;
        if (Session["username"] != null || UserRight.GetUserPermission() == FetConstant.UserRoot)
        {
            username = Session["username"].ToString().ToUpper();
            if (username == FetConstant.Root.ToUpper() || username == FetConstant.Admin)
            {
                if (username == FetConstant.Root.ToUpper())
                {
                    username = string.Empty;
                }
                else
                {
                    cri.add("[" + Friso.Entities.Article._Table + "].[" + ArticleColumns.CreatedBy + "]", FetConstant.ADMINISTRATOR, Condition.NOT_EQUAL, Condition.AND);
                }
            }
            else
            {
                cri.add("[" + Friso.Entities.Article._Table + "].[" + ArticleColumns.CreatedBy + "]", FetConstant.ADMINISTRATOR, Condition.NOT_EQUAL, Condition.AND);
                cri.add("[" + Friso.Entities.Article._Table + "].[" + ArticleColumns.CreatedBy + "]", FetConstant.ADMINS, Condition.NOT_EQUAL, Condition.AND);
                long userid = long.MinValue;
                if (Session["userid"] != null)
                {
                    userid = long.Parse(Session["userid"].ToString());
                }
                Criteria criuser = new Criteria();
                criuser.add("[" + Friso.Entities.User._Table + "].[" + UserColumns.UserId + "]", userid, Condition.NOT_EQUAL, Condition.AND);
                criuser.add("[" + Friso.Entities.User._Table + "].[" + UserColumns.PermissionId + "]", FetConstant.USERROOT, Condition.EQUAL, Condition.AND);
                Friso.Entities.UserCollection _us = UserService.GetUserListByParam(UserColumns.UserId, OrderDirection.ASC, criuser.Criter);
                string iduser = string.Empty;
                foreach (Friso.Entities.User _var in _us)
                {
                    iduser += _var.UserId + ",";
                }
                if (iduser != string.Empty)
                {
                    query = cri.Criter + " And CreatedBy NOT IN(" + iduser.TrimEnd(',') + ")";
                }
                else
                {
                    query = cri.Criter + " And CreatedBy NOT IN(0)";
                }

            }
        }
        else
        {
            Response.Redirect("~/Login.aspx");
        }
        hyperlinkPager.PageSize = RTISettings.PageSize;
        NoCountStart = (hyperlinkPager.PageSize * (hyperlinkPager.CurrentIndex - 1)) + 1;
        int totalrecord = 0;
        ArticleCollection _ArticleCollection = new ArticleCollection();
        long userid_ = long.MinValue;
        if (Session["checked"] != null)
        {
            userid_ = long.Parse(Session["checked"].ToString());
        }
        if (userid_ == FetConstant.USERROOT)
        {
            _ArticleCollection = ArticleService.GetArticleListByParam(hidColSort, OrderDirection.ASC, hyperlinkPager.CurrentIndex, hyperlinkPager.PageSize, query, out totalrecord);
        }
        else
        {
            _ArticleCollection = ArticleService.GetArticleListByParam(hidColSort, OrderDirection.ASC, hyperlinkPager.CurrentIndex, hyperlinkPager.PageSize, cri.Criter, out totalrecord);
        }
        rptList.DataSource = _ArticleCollection;
        rptList.DataBind();
        hyperlinkPager.ItemCount = totalrecord;
        if ((float)totalrecord / (float)hyperlinkPager.PageSize <= 1)
            hyperlinkPager.Visible = false;
    }
    protected void rptList_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Article _Article = (Article)e.Item.DataItem;
            Literal ltrNo = (Literal)e.Item.FindControl("ltrNo");
            Literal ltrName = (Literal)e.Item.FindControl("ltrName");
            TextBox txtOrder = (TextBox)e.Item.FindControl("txtOrder");
            DropDownList ddlStatus = (DropDownList)e.Item.FindControl("ddlStatus");
            CheckBox ckbApprove = (CheckBox)e.Item.FindControl("ckbApprove");
            CheckBox ckbEnable = (CheckBox)e.Item.FindControl("ckbEnable");
            Literal ltrVersion = (Literal)e.Item.FindControl("ltrVersion");
            HiddenField hidID = (HiddenField)e.Item.FindControl("hidID");
            Literal ltrCode = (Literal)e.Item.FindControl("ltrCode");
            Literal ltrDate = (Literal)e.Item.FindControl("ltrDate");
            Literal ltrUser = (Literal)e.Item.FindControl("ltrUser");
            LoadddlStatus(ddlStatus);
            ltrNo.Text = ltrNo.Text = Convert.ToString(NoCountStart + e.Item.ItemIndex);
            hidID.Value = _Article.ArticleId.ToString();
            ltrName.Text = _Article.Title;
            txtOrder.Text = _Article.Order.ToString();
            ddlStatus.SelectedValue = _Article.Status.ToString();
            ckbApprove.Checked = _Article.Approved;
            ckbEnable.Checked = _Article.Enable;
            SubCategory _sub = SubCategoryService.GetSubCategory(_Article.SubCatId);
            if (_sub != null)
            {
                ltrVersion.Text = _sub.Name;
            }
            ltrDate.Text = Utilitys.GetFormattedDate(_Article.CreatedDate);
            Friso.Entities.User _User = UserService.GetUser(_Article.CreatedBy);
            if (_User != null)
                ltrUser.Text = _User.UserName;
        }
    }
    protected void LoadddlStatus(DropDownList ddlStatus)
    {
        ddlStatus.Items.Clear();
        ddlStatus.Items.Add(new ListItem((string)Utilitys.Dictionary["option"], "0"));
        StatuCollection _StatuCollection = StatuService.GetStatuList(StatuColumns.Code, OrderDirection.ASC);
        foreach (Statu _Statu in _StatuCollection)
        {
            ddlStatus.Items.Add(new ListItem(_Statu.Name, _Statu.StatusId.ToString()));
        }
    }
    protected void rptList_OnItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        string commandName = e.CommandName;
        object obj = new object();
        switch (commandName)
        {
            case "sortName":
                obj = "[" + Article._Table + "].[" + ArticleColumns.Title + "]";
                break;
            case "sortOrder":
                obj = "[" + Article._Table + "].[" + ArticleColumns.Order + "]";
                break;
            case "sortStatus":
                obj = "[" + Statu._Table + "].[" + StatuColumns.Name + "]";
                break;
            case "sortUser":
                obj = "[" + Friso.Entities.User._Table + "].[" + UserColumns.UserName + "]";
                break;
            case "sortDate":
                obj = "[" + Article._Table + "].[" + ArticleColumns.CreatedDate + "]";
                break;
            case "sortApprove":
                obj = "[" + Article._Table + "].[" + ArticleColumns.Approved + "]";
                break;
            case "sortVersion":
                obj = "[" + Article._Table + "].[" + ArticleColumns.Version + "]";
                break;
            case "sortEnable":
                obj = "[" + Article._Table + "].[" + ArticleColumns.Enable + "]";
                break;
            default:
                break;
        }
        if (OrderDirection.ASC == OrderDirection.ASC)
            Session["Order"] = OrderDirection.DESC;
        else
            Session["Order"] = OrderDirection.ASC;
        this.hidColSort = obj.ToString();
        LoadData();
    }
    protected void lbtDelete_Onclick(object sender, EventArgs e)
    {
        foreach (RepeaterItem item in this.rptList.Items)
        {
            HtmlInputCheckBox chkDelete = (HtmlInputCheckBox)item.FindControl("chkDelete");
            if (chkDelete.Checked == true)
            {
                HiddenField hidID = (HiddenField)item.FindControl("hidID");
                string strhidID = hidID.Value;
                long ID = long.Parse(strhidID);
                try
                {
                    ArticleService.DeleteArticle(ID);
                }
                catch
                {
                    lb_error.Text = "Dont's delete this item because it is getting using another items";
                }
            }
        }
        LoadData();
    }
    protected void pager_Command(object sender, CommandEventArgs e)
    {
        int currnetPageIndx = Convert.ToInt32(e.CommandArgument);
        hyperlinkPager.CurrentIndex = currnetPageIndx;
        LoadData();
    }
    protected void btnSave_OnClick(object sender, EventArgs e)
    {
        foreach (RepeaterItem item in this.rptList.Items)
        {
            HiddenField hidID = (HiddenField)item.FindControl("hidID");
            CheckBox ckbApprove = (CheckBox)item.FindControl("ckbApprove");
            CheckBox ckbEnable = (CheckBox)item.FindControl("ckbEnable");
            Article _Article = ArticleService.GetArticle(long.Parse(hidID.Value));
            TextBox txtOrder = (TextBox)item.FindControl("txtOrder");
            DropDownList ddlStatus = (DropDownList)item.FindControl("ddlStatus");
            if (_Article != null)
            {
                _Article.Order = int.Parse(txtOrder.Text.Trim());
                _Article.Approved = ckbApprove.Checked;
                _Article.Enable = ckbEnable.Checked;
                _Article.Status = long.Parse(ddlStatus.SelectedValue);
                ArticleService.UpdateArticle(_Article);
            }
        }
        LoadData();
    }
    protected void btnSearch_OnClick(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("ArticleList.aspx?Title={0}&StatusID={1}&SubCatId={2}", txtTitle.Text.Trim(), ddlStatusSearch.SelectedValue, ddlsub.SelectedValue.ToString()));
    }
    protected void btnSearchAll_OnClick(object sender, EventArgs e)
    {
        Response.Redirect("ArticleList.aspx");
    }
}
